package com.example.springsecurity.common.utils;

import com.example.springsecurity.common.config.SystemUserLoginDetail;
import com.example.springsecurity.common.enums.ResultCode;
import com.example.springsecurity.common.exception.BizException;
import com.example.springsecurity.entity.SystemUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * SecurityUtil
 */
public class SecurityUtil {

    /**
     * @Description：获取当前系统登陆人账号
     * @Author：fengcheng
     * @Date：2025/1/21 09:03
     * @Return：java.lang.String
     */
    public static String getSystemUserName() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            SystemUserLoginDetail sysUserDetail = (SystemUserLoginDetail) auth.getPrincipal();
            return sysUserDetail.getSystemUser().getUsername();
        } catch (Exception e) {
            throw new BizException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
        }
    }

    public static SystemUser getSystemUser() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            SystemUserLoginDetail sysUserDetail = (SystemUserLoginDetail) auth.getPrincipal();
            return sysUserDetail.getSystemUser();
        } catch (Exception e) {
            throw new BizException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
        }
    }

    public static UserDetails getUserDetails() {
        UserDetails userDetails;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new BizException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
        }
        return userDetails;
    }

}
